package com.itheima.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.common.R;
import com.itheima.controllerApi.CategoryControllerApi;
import com.itheima.domain.Category;
import com.itheima.service.CategoryService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Slf4j
@RestController
@RequestMapping("/category")
public class CategoryController implements CategoryControllerApi {

    @Autowired
    private CategoryService categoryService;
    @Autowired
    private RedisTemplate redisTemplate;

    //添加菜品
    @PostMapping
    public R categoryAdd(@RequestBody Category category){
        //先查，判断，再增
        String name = category.getName();
        LambdaQueryWrapper<Category> lwq = new LambdaQueryWrapper<>();
        lwq.eq(Category::getName,name);
        Category one = categoryService.getOne(lwq);
        if(one!=null){
            return R.error(name+"已存在");
        }

        categoryService.save(category);

        return R.success("添加菜品成功");
    }

    //分页查询
    @GetMapping("/page")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page",value = "页码",required = true),
            @ApiImplicitParam(name = "pageSize",value = "每页记录数",required = true),
    })
    public R  categoryByPage(Integer page,Integer pageSize){

        Page<Category> pages = new Page<>(page,pageSize);
        LambdaQueryWrapper<Category> lwq = new LambdaQueryWrapper<>();
        //根据sort排序
        lwq.orderByAsc(Category::getSort);
        Page<Category> page1 = categoryService.page(pages, lwq);
        return R.success(page1);
    }

    //删除
    @DeleteMapping
    public R categoryDelete(Long id){
       /* boolean b = categoryService.removeById(id);
        if(!b){
            return R.error("删除失败");
        }
        */
       categoryService.delete(id);
        return R.success("删除成功");
    }

    //修改
    @PutMapping
    public R categoryUpdate(@RequestBody Category category){
        categoryService.updateById(category);
        return R.success("修改分类信息成功");
    }

    //展示菜品类型
    @GetMapping("/list")
    public R categoryTpyes(Category category){


        LambdaQueryWrapper<Category> lqw = new LambdaQueryWrapper<>();
        lqw.eq(category.getType()!=null,  Category::getType,category.getType());
        lqw.orderByAsc(Category::getSort).orderByDesc(Category::getUpdateTime);
        List<Category> list = categoryService.list(lqw);


        return R.success(list);
    }
}
